<template>
  <div class="box">
    <div class="searcharea">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="24">
          <div class="query">
            <el-form :inline="true" :model="querySchedulingPlanParam" class="demo-form-inline">
              <el-form-item label="计划名称">
                <el-input
                  v-model="querySchedulingPlanParam.SchedulingPlanName"
                  placeholder="请输入"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :icon="Search" @click="SearchSchedulingPlan()">搜索</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="contentarea">
      <!-- 功能按钮 -->
      <el-row>
        <el-col :span="24">
          <div class="functionbutton">
            <el-button type="primary" plain @click="addSchedulingPlan()">添加</el-button>
            <el-button type="danger" plain @click="batchDeletionSchedulingPlan()">批量删除</el-button>
          </div>
        </el-col>
      </el-row>

      <!-- 数据表格 -->
      <el-row>
        <el-col :span="24">
          <div>
            <el-table
              v-loading="tableloading"
              :data="tableData"
              border
              style="width: 100%"
              max-height="400px"
              :selection="selectedRows"
              @selection-change="handleSelectionChange"
              @row-click="getRowkey"
              show-overflow-tooltip
              empty-text="暂无数据"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" />
              <el-table-column prop="schedulingPlanNo" label="计划编码" width="180">
                <template #default="scope">
                  <el-button type="text" @click="handleUpdateSchedulingPlanClick(scope.row.id)">
                    {{ scope.row.schedulingPlanNo }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column prop="schedulingPlanName" label="计划名称" width="180" />
              <el-table-column prop="teamBill.teamNo" label="班组编号" width="180" />
              <el-table-column prop="teamBill.teamName" label="班组名称" width="180" />
              <el-table-column prop="productionLine.productionLineName" label="产线名称" width="180" />
              <el-table-column prop="schedulingPlanStatus" label="状态" width="120" align="center">
                <template #default="scope">
                  <el-button type="info" round size="small" v-if="scope.row.schedulingPlanStatus === 0">草稿</el-button>
                  <el-button type="primary" round size="small" v-else-if="scope.row.schedulingPlanStatus === 1"
                    >启用</el-button
                  >
                </template>
              </el-table-column>
              <el-table-column prop="shiftPattern" label="轮班方式" width="140" align="center">
                <template #default="scope">
                  <el-button type="success" round size="small" v-if="scope.row.shiftPattern === 0">白班</el-button>
                  <el-button type="primary" round size="small" v-else-if="scope.row.shiftPattern === 1"
                    >两班倒</el-button
                  >
                  <el-button type="warning" round size="small" v-if="scope.row.shiftPattern === 2">三班倒</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="startTime" label="开始时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="endTime" label="结束时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="remark" label="备注" width="180" />
              <el-table-column prop="creator" label="创建人" />
              <el-table-column prop="updator" label="修改人" />
              <el-table-column prop="createtime" label="创建时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="updateDate" label="更新时间" width="180" :formatter="formatColumnTime" />
              <el-table-column fixed="right" label="操作" width="230">
                <template #default="scope">
                  <el-button
                    type="success"
                    size="small"
                    plain
                    @click="ScheduledTaskOperate(scope.row.id, scope.row.workOrderId)"
                    >分配任务</el-button
                  >
                  <el-button type="danger" plain size="small" @click="DeleteSchedulingPlanSingle(scope.row.id)">
                    删除
                  </el-button>
                  <el-button type="primary" plain size="small" @click="UpdateSchedulingPlan(scope.row)">更新</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <el-row>
        <el-col :span="24">
          <div class="demo-pagination-block" style="display: flex; justify-content: flex-end">
            <el-config-provider :locale="zhCn">
              <el-pagination
                v-model:current-page="querySchedulingPlanParam.PageIndex"
                v-model:page-size="querySchedulingPlanParam.PageSize"
                :page-sizes="[100, 200, 300, 400]"
                :small="false"
                :disabled="false"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="querySchedulingPlanParam.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              >
              </el-pagination>
            </el-config-provider>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 添加 -->
    <div>
      <!-- 添加计划 -->
      <el-dialog
        v-model="centerDialogVisible"
        :fullscreen="isFullScreen"
        width="66%"
        append-to-body
        :show-close="false"
        :before-close="CreateSchedulingPlanhandleClose"
      >
        <template #header="{ titleId, titleClass }">
          <div class="my-header">
            <span :id="titleId" :class="titleClass">添加计划</span>
            <div class="header-buttons">
              <el-icon @click="toggleFullScreen" class="icon-button">
                <FullScreen v-if="!isFullScreen" /><CopyDocument v-else />
              </el-icon>
              <el-icon @click="CreateSchedulingPlanhandleClose" class="icon-button full-screen-btn"><Close /></el-icon>
            </div>
          </div>
        </template>

        <el-scrollbar :max-height="maxHeight + 'px'">
          <div>
            <el-row>
              <el-col :span="24">
                <el-form
                  :inline="true"
                  ref="CreateSchedulingPlanFormRef"
                  :model="CreateSchedulingPlanForm"
                  label-width="auto"
                  class="demo-form-inline"
                  :rules="CreateSchedulingPlanFormRules"
                >
                  <el-form-item label="计划编码" prop="SchedulingPlanNO">
                    <el-input
                      v-model="CreateSchedulingPlanForm.SchedulingPlanNO"
                      placeholder="不输入则自动生成"
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="SchedulingPlanName" label="计划名称">
                    <el-input
                      v-model="CreateSchedulingPlanForm.SchedulingPlanName"
                      placeholder="请输入计划名称"
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>

                  <el-form-item label="开始时间" prop="StartTime">
                    <el-config-provider :locale="zhCn">
                      <el-date-picker
                        v-model="CreateSchedulingPlanForm.StartTime"
                        type="datetime"
                        placeholder="请选择日期和时间"
                        :size="size"
                        style="width: 270px"
                      />
                    </el-config-provider>
                  </el-form-item>

                  <el-form-item label="结束时间" prop="EndTime">
                    <el-config-provider :locale="zhCn">
                      <el-date-picker
                        v-model="CreateSchedulingPlanForm.EndTime"
                        type="datetime"
                        placeholder="请选择"
                        :size="size"
                        style="width: 270px"
                      />
                    </el-config-provider>
                  </el-form-item>
                  <el-form-item label="状态">
                    <el-radio-group v-model="CreateSchedulingPlanForm.SchedulingPlanStatus" style="width: 270px">
                      <el-radio :value="0">草稿</el-radio>
                      <el-radio :value="1">启用</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="班组" prop="TeamBillId">
                    <el-link style="width: 270px" @click="SelectTeamBill">
                      <span
                        v-if="
                          CreateSchedulingPlanForm.TeamBillId === '' || CreateSchedulingPlanForm.TeamBillId === null
                        "
                      >
                        <el-icon class="el-icon--left">
                          <el-icon><CirclePlus /></el-icon> </el-icon
                        >选择班组
                      </span>
                      <span v-else> {{ CreateSchedulingPlanForm.TeamBillName }} </span>
                    </el-link>
                  </el-form-item>
                  <el-form-item label="轮班方式" prop="ShiftPattern">
                    <el-segmented
                      style="width: 270px"
                      v-model="CreateSchedulingPlanForm.ShiftPattern"
                      :options="[
                        { label: '三班倒', value: 2 },
                        { label: '两班倒', value: 1 },
                        { label: '白班', value: 0 }
                      ]"
                    />
                  </el-form-item>
                  <el-form-item label="产线" prop="ProductionLineId">
                    <el-link style="width: 270px" @click="SelectProductionLine">
                      <span
                        v-if="
                          CreateSchedulingPlanForm.WorkStationName === '' ||
                          CreateSchedulingPlanForm.WorkStationName === null
                        "
                      >
                        <el-icon class="el-icon--left">
                          <el-icon><CirclePlus /></el-icon> </el-icon
                        >选择产线
                      </span>
                      <span v-else> {{ CreateSchedulingPlanForm.WorkStationName }} </span>
                    </el-link>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-divider content-position="left">员工列表</el-divider>

            <!-- 班组明细数据表格 -->
            <el-row>
              <el-col :span="24">
                <el-tabs type="border-card">
                  <el-tab-pane label="班组成员">
                    <el-row>
                      <el-col :span="24">
                        <el-table
                          :data="CreateProductcurrentPageData"
                          border
                          style="width: 100%"
                          max-height="400px"
                          show-overflow-tooltip
                          empty-text="暂无数据"
                        >
                          <el-table-column type="selection" width="55" />
                          <el-table-column type="index" label="序号" width="60" />
                          <el-table-column prop="jobNumber" label="工号" />
                          <el-table-column prop="userName" label="姓名" />
                          <el-table-column prop="department.departmentName" label="部门" />
                          <el-table-column prop="roleinfo.roleName" label="职称" />
                          <el-table-column prop="role" label="工作站台" width="180">
                            <template #default="scope">
                              <!--   @change="filteredWorkStationtableData(scope.row.WorkStationId)" -->
                              <el-select
                                v-model="scope.row.WorkStationId"
                                filterable
                                placeholder="请选择工作站"
                                clearable
                                @change="WorkStationtSelectionChange(scope.row.WorkStationId)"
                                @clear="WorkStationtSelectionClear(scope.row)"
                                :disabled="scope.row.Status >= 1"
                              >
                                <el-option
                                  v-for="option in filteredWorkStationtableData(scope.row.WorkStationId)"
                                  :key="option.id"
                                  :label="option.workStationName"
                                  :value="option.id"
                                />
                              </el-select>
                            </template>
                          </el-table-column>
                          <el-table-column prop="processName" label="工序" />

                          <el-table-column prop="role" label="状态" width="230">
                            <template #default="scope">
                              <el-segmented
                                style="width: 200px"
                                v-model="scope.row.Status"
                                @change="handleStatusChange(scope.row)"
                                :options="[
                                  { label: '正常', value: 0 },
                                  { label: '休假', value: 2 },
                                  { label: '请假', value: 1 }
                                ]"
                              />
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-col>
                    </el-row>

                    <!-- 分页 -->
                    <el-row>
                      <el-col :span="24">
                        <div style="display: flex; justify-content: flex-end; margin-top: 10px">
                          <el-config-provider :locale="zhCn">
                            <el-pagination
                              @size-change="CreateProducthandleSizeChange"
                              @current-change="CreateProducthandleCurrentChange"
                              :current-page="CreateProductcurrentPage"
                              :page-sizes="[10, 20, 50, 100]"
                              :page-size="CreateProductpageSize"
                              layout="total, sizes, prev, pager, next, jumper"
                              :total="CreateProductTotalItems"
                            />
                          </el-config-provider>
                        </div>
                      </el-col>
                    </el-row>
                  </el-tab-pane>
                </el-tabs>
              </el-col>
            </el-row>
          </div>
        </el-scrollbar>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="CreateSchedulingPlanhandleClose">取消</el-button>
            <el-button type="primary" @click="CreateSchedulingPlanDialog(CreateSchedulingPlanFormRef)">提交</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 选择班组信息 -->
      <ChildComponent
        :querycolumns="querycolumns"
        :columns="columns"
        :data="SelectTeamBillBilltableData"
        :dialogVisible="SelectTeamBillBillDialogVisible"
        @selected="handleSelectedTeamBillBillData"
        @closed="handleDialogClosedTeamBillBill"
        @QueryForm="QueryTeamBillBillForms"
      />
      <!-- 选择产线信息 -->
      <ChildComponent
        :querycolumns="queryProductionLineColumns"
        :columns="ProductionLineColumns"
        :data="SelectProductionLinetableData"
        :dialogVisible="SelectProductionLineDialogVisible"
        @selected="handleSelectedProductionLineData"
        @closed="handleDialogClosedProductionLine"
        @QueryForm="QueryProductionLineForms"
      />
    </div>

    <!-- 修改 -->
    <div>
      <!-- 添加计划 -->
      <el-dialog
        v-model="UpdateDialogVisible"
        :fullscreen="isFullScreen"
        width="66%"
        append-to-body
        :show-close="false"
        :before-close="UpdateSchedulingPlanhandleClose"
      >
        <template #header="{ titleId, titleClass }">
          <div class="my-header">
            <span :id="titleId" :class="titleClass">更新计划</span>
            <div class="header-buttons">
              <el-icon @click="toggleFullScreen" class="icon-button">
                <FullScreen v-if="!isFullScreen" /><CopyDocument v-else />
              </el-icon>
              <el-icon @click="UpdateSchedulingPlanhandleClose" class="icon-button full-screen-btn"><Close /></el-icon>
            </div>
          </div>
        </template>

        <el-scrollbar :max-height="maxHeight + 'px'">
          <div>
            <el-row>
              <el-col :span="24">
                <el-form
                  :inline="true"
                  class="demo-form-inline"
                  ref="UpdateSchedulingPlanFormRef"
                  :model="UpdateSchedulingPlanForm"
                  label-width="auto"
                  :rules="CreateSchedulingPlanFormRules"
                >
                  <el-form-item label="计划编码" prop="SchedulingPlanNo">
                    <el-input
                      v-model="UpdateSchedulingPlanForm.SchedulingPlanNo"
                      placeholder="不输入则自动生成"
                      disabled
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="SchedulingPlanName" label="计划名称">
                    <el-input
                      v-model="UpdateSchedulingPlanForm.SchedulingPlanName"
                      placeholder="请输入计划名称"
                      style="width: 270px"
                    >
                    </el-input>
                  </el-form-item>

                  <el-form-item label="开始时间" prop="StartTime">
                    <el-config-provider :locale="zhCn">
                      <el-date-picker
                        v-model="UpdateSchedulingPlanForm.StartTime"
                        type="datetime"
                        placeholder="请选择日期和时间"
                        :size="size"
                        style="width: 270px"
                      />
                    </el-config-provider>
                  </el-form-item>

                  <el-form-item label="结束时间" prop="EndTime">
                    <el-config-provider :locale="zhCn">
                      <el-date-picker
                        v-model="UpdateSchedulingPlanForm.EndTime"
                        type="datetime"
                        placeholder="请选择"
                        :size="size"
                        style="width: 270px"
                      />
                    </el-config-provider>
                  </el-form-item>
                  <el-form-item label="状态">
                    <el-radio-group v-model="UpdateSchedulingPlanForm.SchedulingPlanStatus" style="width: 270px">
                      <el-radio :value="0">草稿</el-radio>
                      <el-radio :value="1">启用</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="班组" prop="TeamBillId">
                    <el-input v-model="UpdateSchedulingPlanForm.TeamName" disabled style="width: 270px" />
                  </el-form-item>
                  <el-form-item label="轮班方式" prop="ShiftPattern">
                    <el-segmented
                      style="width: 270px"
                      v-model="UpdateSchedulingPlanForm.ShiftPattern"
                      :options="[
                        { label: '三班倒', value: 2 },
                        { label: '两班倒', value: 1 },
                        { label: '白班', value: 0 }
                      ]"
                    />
                  </el-form-item>
                  <el-form-item label="产线" prop="ProductionLineId">
                    <el-link style="width: 270px" @click="UpdateSelectProductionLine">
                      <span
                        v-if="
                          UpdateSchedulingPlanForm.ProductionLineName === '' ||
                          UpdateSchedulingPlanForm.ProductionLineName === null
                        "
                      >
                        <el-icon class="el-icon--left">
                          <el-icon><CirclePlus /></el-icon> </el-icon
                        >选择产线
                      </span>
                      <span v-else> {{ UpdateSchedulingPlanForm.ProductionLineName }} </span>
                    </el-link>
                  </el-form-item>
                </el-form>
              </el-col>
            </el-row>
            <el-divider content-position="left">员工列表</el-divider>

            <!-- 班组明细数据表格 -->
            <el-row>
              <el-col :span="24">
                <el-tabs type="border-card">
                  <el-tab-pane label="班组成员">
                    <el-row>
                      <el-col :span="24">
                        <el-table
                          :data="UpdateProductcurrentPageData"
                          border
                          style="width: 100%"
                          max-height="400px"
                          show-overflow-tooltip
                          empty-text="暂无数据"
                        >
                          <el-table-column type="selection" width="55" />
                          <el-table-column type="index" label="序号" width="60" />
                          <el-table-column prop="jobNumber" label="工号" />
                          <el-table-column prop="userName" label="姓名" />
                          <el-table-column prop="departmentName" label="部门" />
                          <el-table-column prop="workStationId" label="工作站台" width="180">
                            <template #default="scope">
                              <!--   @change="filteredWorkStationtableData(scope.row.WorkStationId)" -->
                              <el-select
                                v-model="scope.row.workStationId"
                                filterable
                                placeholder="请选择工作站"
                                clearable
                                @change="UpdateWorkStationtSelectionChange(scope.row.id, scope.row.workStationId)"
                                @clear="UpdateWorkStationtSelectionClear(scope.row)"
                                :disabled="scope.row.status >= 1"
                              >
                                <el-option
                                  v-for="option in UpdatefilteredWorkStationtableData(scope.row.workStationId)"
                                  :key="option.id"
                                  :label="option.workStationName"
                                  :value="option.id"
                                />
                              </el-select>
                            </template>
                          </el-table-column>
                          <el-table-column prop="processName" label="工序" />

                          <el-table-column prop="role" label="状态" width="230">
                            <template #default="scope">
                              <el-segmented
                                style="width: 200px"
                                v-model="scope.row.status"
                                @change="UpdatehandleStatusChange(scope.row)"
                                :options="[
                                  { label: '正常', value: 0 },
                                  { label: '休假', value: 2 },
                                  { label: '请假', value: 1 }
                                ]"
                              />
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-col>
                    </el-row>

                    <!-- 分页 -->
                    <el-row>
                      <el-col :span="24">
                        <div style="display: flex; justify-content: flex-end; margin-top: 10px">
                          <el-config-provider :locale="zhCn">
                            <el-pagination
                              @size-change="UpdateProducthandleSizeChange"
                              @current-change="UpdateProducthandleCurrentChange"
                              :current-page="UpdateProductcurrentPage"
                              :page-sizes="[10, 20, 50, 100]"
                              :page-size="UpdateProductpageSize"
                              layout="total, sizes, prev, pager, next, jumper"
                              :total="UpdateProductTotalItems"
                            />
                          </el-config-provider>
                        </div>
                      </el-col>
                    </el-row>
                  </el-tab-pane>
                </el-tabs>
              </el-col>
            </el-row>
          </div>
        </el-scrollbar>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="UpdateSchedulingPlanhandleClose">取消</el-button>
            <el-button type="primary" @click="UpdateSchedulingPlanDialog(UpdateSchedulingPlanFormRef)">提交</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 选择产线信息 -->
      <ChildComponent
        :querycolumns="queryProductionLineColumns"
        :columns="ProductionLineColumns"
        :data="SelectProductionLinetableData"
        :dialogVisible="UpdateSelectProductionLineDialogVisible"
        @selected="UpdatehandleSelectedProductionLineData"
        @closed="handleDialogClosedProductionLine"
        @QueryForm="QueryProductionLineForms"
      />
    </div>

    <!-- 按排任务 -->
    <div>
      <el-dialog
        v-model="ScheduledTaskDialogVisible"
        :fullscreen="isFullScreen"
        width="66%"
        append-to-body
        :show-close="false"
        :before-close="ScheduledTaskhandleClose"
      >
        <template #header="{ titleId, titleClass }">
          <div class="my-header">
            <span :id="titleId" :class="titleClass">分配任务</span>
            <div class="header-buttons">
              <el-icon @click="toggleFullScreen" class="icon-button">
                <FullScreen v-if="!isFullScreen" /><CopyDocument v-else />
              </el-icon>
              <el-icon @click="ScheduledTaskhandleClose" class="icon-button full-screen-btn"><Close /></el-icon>
            </div>
          </div>
        </template>

        <el-scrollbar :max-height="maxHeight + 'px'">
          <div>
            <el-row>
              <el-col :span="24">
                <el-form
                  style="padding: 0"
                  :inline="true"
                  ref="CreateSchedulingPlanFormRef"
                  :model="CreateSchedulingPlanForm"
                  label-width="auto"
                  class="demo-form-inline"
                  :rules="CreateSchedulingPlanFormRules"
                >
                  <el-form-item label="生产工单" prop="WorkStationName">
                    <el-link style="width: 270px" @click="SelectWorkOrderTask">
                      <span v-if="WorkOrderParam.workOrderName === '' || WorkOrderParam.workOrderName === null">
                        <el-icon class="el-icon--left">
                          <el-icon><CirclePlus /></el-icon> </el-icon
                        >选择生产工单
                      </span>
                      <span v-else> {{ WorkOrderParam.workOrderName }} </span>
                    </el-link>
                  </el-form-item>
                </el-form>
                <el-card shadow="never">
                  <template #header>
                    <div class="card-header">
                      <span v-if="WorkOrderParam.workOrderName != null">
                        生产任务总数： <el-tag size="small">{{ WorkOrderParam.orderQuantity }}</el-tag> 个
                      </span>
                      <span v-else> 请选择工单 </span>
                    </div>
                  </template>

                  <div v-if="Production_WorkOrderTasks.length > 0">
                    <el-row :gutter="24">
                      <el-col
                        :span="6"
                        v-for="(item, colIndex) in Production_WorkOrderTasks"
                        :key="colIndex"
                        style="margin-bottom: 10px"
                      >
                        <div class="grid-content ep-bg-purple">
                          {{ item.materialsName }}:
                          <el-tag size="small" type="primary">{{ item.allocatedQuantity }}</el-tag> /
                          <el-tag size="small" type="success"> {{ item.quantity }}</el-tag>
                        </div>
                      </el-col>
                    </el-row>
                  </div>
                  <div v-else>空</div>
                </el-card>
              </el-col>
            </el-row>

            <el-divider content-position="left">人员列表</el-divider>

            <!-- 成员明细数据表格 -->
            <el-row>
              <el-col :span="24">
                <el-tabs type="border-card">
                  <el-tab-pane label="成员">
                    <el-row>
                      <el-col :span="24">
                        <el-table
                          :data="ScheduledTaskSchedulingPlanDetial"
                          border
                          style="width: 100%"
                          max-height="400px"
                          show-overflow-tooltip
                          empty-text="暂无数据"
                        >
                          <el-table-column type="selection" width="55" />
                          <el-table-column type="index" label="序号" width="60" />
                          <el-table-column prop="userinfo.jobNumber" label="工号" />
                          <el-table-column prop="userinfo.userName" label="姓名" />

                          <el-table-column prop="workStation.workStationName" label="工作站台" width="180">
                          </el-table-column>
                          <el-table-column prop="workStation.process.processName" label="工序" />
                          <el-table-column prop="materialId" label="任务名称">
                            <template #default="scope">
                              <el-select v-model="scope.row.materialId" filterable placeholder="请选择任务" clearable>
                                <el-option
                                  v-for="option in Production_WorkOrderTasks"
                                  :key="option.materialId"
                                  :label="option.materialsName"
                                  :value="option.materialId"
                                />
                              </el-select>
                            </template>
                          </el-table-column>
                          <el-table-column prop="schedulingQuantity" label="任务数量">
                            <template #default="scope">
                              <el-input-number
                                v-model="scope.row.schedulingQuantity"
                                :min="1"
                                :max="99999"
                                style="width: 100%"
                                @change="SchedulingQuantityhandleChange(scope.row)"
                              />
                            </template>
                          </el-table-column>
                        </el-table>
                      </el-col>
                    </el-row>

                    <!-- 分页 -->
                    <el-row>
                      <el-col :span="24">
                        <div style="display: flex; justify-content: flex-end; margin-top: 10px">
                          <el-config-provider :locale="zhCn">
                            <el-pagination
                              @size-change="CreateProducthandleSizeChange"
                              @current-change="CreateProducthandleCurrentChange"
                              :current-page="CreateProductcurrentPage"
                              :page-sizes="[10, 20, 50, 100]"
                              :page-size="CreateProductpageSize"
                              layout="total, sizes, prev, pager, next, jumper"
                              :total="CreateProductTotalItems"
                            />
                          </el-config-provider>
                        </div>
                      </el-col>
                    </el-row>
                  </el-tab-pane>
                </el-tabs>
              </el-col>
            </el-row>
          </div>
        </el-scrollbar>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="ScheduledTaskhandleClose">取消</el-button>
            <el-button type="primary" @click="CreateWorkOrderTaskDialog()">提交</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 选择工单信息 -->
      <ChildComponent
        :querycolumns="queryWorkOrderTaskColumns"
        :columns="WorkOrderTaskColumns"
        :data="SelectWorkOrdertableData"
        :dialogVisible="SelectWorkOrderDialogVisible"
        @selected="handleSelectedWorkOrderTaskData"
        @closed="ScheduledWorkOrderTaskhandleClose"
        @QueryForm="QueryTeamBillBillForms"
      />
    </div>
  </div>
</template>


<script setup lang="ts">
import ChildComponent from '@/components/CustomSelectDataDialog.vue'

import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessageBox, ElNotification, FormInstance } from 'element-plus'
import {
  ApiUpdateCrew_SchedulingPlanDetialByIdAsync,
  ApiGetCrew_SchedulingPlanByIdDetialsPageListAsync,
  ApiUpdateCrew_SchedulingPlanByBindWorkOrderAsync,
  ApiGetCrew_SchedulingPlanByIdAsync,
  ApiGetCrew_SchedulingPlanPageListAsync,
  ApiDeletionCrew_SchedulingPlanAsync,
  ApiCreateCrew_SchedulingPlanAsync,
  ApiUpdateCrew_SchedulingPlanAsync
} from '../../api/crew/CrewSchedulingPlan'

import {
  ApiGetCrew_TeamBillPageListAsync,
  ApiGetCrew_TeamBillDetialPageListAsync
} from '../../api/crew/CrewTeamBillApi'

import {
  ApiGetShopfloor_ProductionLinePageListAsync,
  ApiGetShopfloor_ProductionLineByIdWorkStationListAsync
} from '../../api/shopfloor/ShopfloorProductionLineApi'
import {
  ApiGetProduction_WorkOrderPageListAsync,
  ApiGetProduction_WorkOrderByIdTaskListAsync
} from '../../api/production/ProductionWorkOrderApi'

import { formatTime, capitalizeFirstLetter } from '../../utils/index'
import {
  ApiCreateProduction_ProductionTaskAsync,
  ApiCreateProduction_ProductionTaskBySchedulingPlanDetialIdAsync
} from '../../api/production/ProductionProductionTaskApi'
import { id } from 'element-plus/es/locale'
interface SchedulingPlan {
  id: string
}

// ------------------------修改------------------------------

// 分页相关数据
const UpdateProductcurrentPage = ref(1)
const UpdateProductpageSize = ref(10)

// 计算当前页要显示的数据
const UpdateProductcurrentPageData = computed(() => {
  const startIndex = (CreateProductcurrentPage.value - 1) * UpdateProductpageSize.value
  const endIndex = Math.min(startIndex + UpdateProductpageSize.value, UpdateCrewSchedulingPlanDetial.value.length)
  return UpdateCrewSchedulingPlanDetial.value.slice(startIndex, endIndex)
})

// 总条目数
const UpdateProductTotalItems = computed(() => UpdateCrewSchedulingPlanDetial.value.length)

// 处理分页大小变化的方法
const UpdateProducthandleSizeChange = (val: number) => {
  UpdateProductpageSize.value = val
  UpdateProductcurrentPage.value = 1 // 重置页码为 1
}

// 处理当前页变化的方法
const UpdateProducthandleCurrentChange = (val: number) => {
  UpdateProductcurrentPage.value = val
}

// 存储所有选中的值
const UpdateWorkStationtSelectedValues = ref([])

// 计算过滤后的选项列表
const UpdatefilteredWorkStationtableData = (row: string) => {
  return UpdateWorkStationtableData.value.filter((option) => {
    // 仅包含未被选中的选项或当前行选中的选项
    return !UpdateWorkStationtSelectedValues.value.includes(option.id) || option.id === row
  })
}

// 处理选中值改变事件
const UpdateWorkStationtSelectionChange = (SchedulingPlanDetialId: string, WorkStationId: string) => {
  const WorkStationt = UpdateWorkStationtableData.value.find((item) => item.id == WorkStationId)

  // 向TeamBillDetialData添加一个工序值
  if (WorkStationt !== null) {
    //  processName 值
    const newProcessName = WorkStationt?.process.processName

    // 找到匹配的对象，并更新它
    const updatedValue = UpdateCrewSchedulingPlanDetial.value.map((item) => {
      if (item.workStationId === WorkStationId) {
        // 如果找到匹配的 WorkStationId，复制原对象，并添加新的 processName 属性
        return {
          ...item,
          processName: newProcessName
        }
      }
      return item // 对于非匹配项，保持不变
    })

    //更新信息
    const crewSchedulingPlanDetial = UpdateCrewSchedulingPlanDetial.value.find((g) => g.id === SchedulingPlanDetialId)
    ApiUpdateCrew_SchedulingPlanDetialByIdAsync(crewSchedulingPlanDetial).then((res) => {
      ElNotification({
        message: '设置成功',
        offset: 100,
        type: 'success',
        duration: 2000
      })
    })

    // 更新 TeamBillDetialData.value 的值为更新后的数组
    UpdateCrewSchedulingPlanDetial.value = updatedValue
  }
  updateSchedulingPlanSelectedValues()
}

// 更新选中的值列表
const updateSchedulingPlanSelectedValues = () => {
  UpdateWorkStationtSelectedValues.value = UpdateCrewSchedulingPlanDetial.value
    .map((data) => data.workStationId)
    .filter((value) => value)
}

//设置员工休息
const UpdatehandleStatusChange = (row: any) => {
  if (row.status >= 1) {
    UpdateWorkStationtSelectionClear(row)
    row.processName = null
    //更新信息
    ApiUpdateCrew_SchedulingPlanDetialByIdAsync(row).then((res) => {
      ElNotification({
        message: '设置成功',
        offset: 100,
        type: 'success',
        duration: 2000
      })
    })
  }
}

// 处理清除选中值事件
const UpdateWorkStationtSelectionClear = (row: any) => {
  // 清除当前行的选中值
  row.workStationId = null
  updateSchedulingPlanSelectedValues()
}

//打开选择产线对话框
const UpdateSelectProductionLine = () => {
  UpdateSelectProductionLineDialogVisible.value = true
  ApiGetShopfloor_ProductionLinePageListAsync(queryProductionLineParam).then((res) => {
    SelectProductionLinetableData.value = res.data.data
    queryProductionLineParam.PageIndex = res.data.pageIndex
    queryProductionLineParam.PageSize = res.data.pageSize
    queryProductionLineParam.totalCount = res.data.totalCount
  })
}

const UpdateSelectProductionLineDialogVisible = ref(false)

//选择工作站对话框确定操作
const UpdatehandleSelectedProductionLineData = (selectedData: ProductionLine[]) => {
  if (selectedData && selectedData.length == 1) {
    const rowdata = selectedData.values().next().value
    UpdateSchedulingPlanForm.ProductionLineId = rowdata.id
    UpdateSchedulingPlanForm.ProductionLineName = rowdata.productionLineName

    // 获取明细
    ApiGetShopfloor_ProductionLineByIdWorkStationListAsync(rowdata.id).then((res) => {
      UpdateWorkStationtableData.value = res.data.data

      UpdateCrewSchedulingPlanDetial.value.forEach((data) => {
        data.workStationId = null
        data.processName = null
      })
      UpdateWorkStationtSelectedValues.value = []
    })
  } else if (selectedData.length > 1) {
    ElNotification({
      message: '只有选择一条信息，请重新选择',
      offset: 100,
      type: 'warning',
      duration: 2000
    })
  }

  // 清空工作站台存储所有选中的值
  WorkStationtSelectedValues.value = []
}

//工作站表格数据
const UpdateWorkStationtableData = ref([{ id: null }])

//计划表格明细数据
const UpdateCrewSchedulingPlanDetial = ref([{ id: null, workStationId: null, processName: null }])

// 打开修改计划窗口
const handleUpdateSchedulingPlanClick = (id: string) => {
  UpdateDialogVisible.value = true
  ApiGetCrew_SchedulingPlanByIdAsync(id).then((res) => {
    Object.assign(UpdateSchedulingPlanForm, capitalizeFirstLetter(res.data.data))
    UpdateCrewSchedulingPlanDetial.value = res.data.data.crewSchedulingPlanDetial

    // 将已选的工作站台给到UpdateWorkStationtSelectedValues
    res.data.data.crewSchedulingPlanDetial.forEach((item) => {
      if (item.workStationId) {
        UpdateWorkStationtSelectedValues.value.push(item.workStationId)
      }
    })

    // 根据产线id获取工作站台列表
    ApiGetShopfloor_ProductionLineByIdWorkStationListAsync(res.data.data.productionLineId).then((res) => {
      UpdateWorkStationtableData.value = res.data.data
    })
  })
}

// 关闭修改计划窗口
const UpdateSchedulingPlanhandleClose = () => {
  UpdateDialogVisible.value = false
}

// -------------------------按排任务------------------------------
const ProductionTaskByDetialDTO = reactive({
  Id: null,
  MaterialId: null,
  WorkOrderId: '',
  billOfMaterialId: null,
  ProductionTaskName: null,
  SchedulingQuantity: 0
})

const SchedulingQuantityhandleChange = (res: { materialId: null; id: null; schedulingQuantity: 0 }) => {
  const workOrderTasks = Production_WorkOrderTasks.value.find((g) => g.materialId === res.materialId)
  // 赋值
  Object.assign(ProductionTaskByDetialDTO, {
    Id: res.id,
    MaterialId: res.materialId,
    billOfMaterialId: workOrderTasks?.billOfMaterialId,
    ProductionTaskName: workOrderTasks?.materialsName,
    SchedulingQuantity: res.schedulingQuantity
  })

  ApiCreateProduction_ProductionTaskBySchedulingPlanDetialIdAsync(ProductionTaskByDetialDTO).then((res) => {
    if (res.data.data) {
      ElNotification({
        message: '分配成功',
        offset: 100,
        type: 'success',
        duration: 2000
      })
      // 获取生产任务
      ApiGetProduction_WorkOrderByIdTaskListAsync(ProductionTaskByDetialDTO.WorkOrderId).then((res) => {
        Production_WorkOrderTasks.value = res.data.data.production_WorkOrderTasks
      })
    }
  })

  // const task = Production_WorkOrderTasks.value.find((task) => task.materialId === res.MaterialId)
  // if (task) {
  //   task.quantity = task.quantity - res.SchedulingQuantity
  // }
  // console.log('Production_WorkOrderTasks.value', Production_WorkOrderTasks.value)
}

// 工单查询参数
const queryWorkOrderParam = reactive({
  WorkOrderName: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 工单实体
const WorkOrderParam = reactive({ workOrderName: null })
const Production_WorkOrderTasks = ref([
  { id: null, materialsName: null, materialId: null, billOfMaterialId: null, quantity: 0 }
])

// 选择工单查询列
const queryWorkOrderTaskColumns = [
  { prop: 'WorkOrderNo', label: '工单编码' },
  { prop: 'WorkOrderName', label: '工单名称' }
]

// 选择工单表格列
const WorkOrderTaskColumns = [
  { prop: 'workOrderNO', label: '工单编码' },
  { prop: 'workOrderName', label: '工单名称' },
  { prop: 'productBill.productBillNo', label: '产品编码' },
  { prop: 'productBill.productBillName', label: '产品名称' },
  { prop: 'orderQuantity', label: '订单数量' }
]

// 按排任务对话框状态
const SelectWorkOrderDialogVisible = ref(false)

// 按排任务对话框表格数据
const SelectWorkOrdertableData = ref([])

// 查询参数
const ScheduledTaskQueryParam = reactive({
  SchedulingPlanId: '',
  WorkOrderId: '',
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 人员表格数据
const ScheduledTaskSchedulingPlanDetial = ref([])

//打开选择工单对话框
const SelectWorkOrderTask = () => {
  SelectWorkOrderDialogVisible.value = true
  ApiGetProduction_WorkOrderPageListAsync(queryWorkOrderParam).then((res) => {
    SelectWorkOrdertableData.value = res.data.data
  })
}
//关闭选择工单对话框
const ScheduledWorkOrderTaskhandleClose = () => {
  SelectWorkOrderDialogVisible.value = false
}

// 关闭创建任务对话框
const ScheduledTaskhandleClose = () => {
  ScheduledTaskDialogVisible.value = false
  Production_WorkOrderTasks.value = []
  WorkOrderParam.workOrderName = null
  SearchSchedulingPlan()
}

// 按排任务对话框状态
const ScheduledTaskDialogVisible = ref(false)

//打开按排任务对话框操作
const ScheduledTaskOperate = (id: string, workOrderId: string) => {
  Production_WorkOrderTasks.value = []
  ScheduledTaskDialogVisible.value = true
  ScheduledTaskQueryParam.SchedulingPlanId = id

  //判断是否已绑定工单
  if (workOrderId !== null) {
    // 获取生产任务
    ApiGetProduction_WorkOrderByIdTaskListAsync(workOrderId).then((res) => {
      Object.assign(WorkOrderParam, res.data.data)
      Production_WorkOrderTasks.value = res.data.data.production_WorkOrderTasks
      ProductionTaskByDetialDTO.WorkOrderId = res.data.data.id
    })
  }

  //获取明细
  ApiGetCrew_SchedulingPlanByIdDetialsPageListAsync(ScheduledTaskQueryParam).then((res) => {
    ScheduledTaskSchedulingPlanDetial.value = res.data.data
  })
}

//选择工单对话框确定操作
const handleSelectedWorkOrderTaskData = (selectedData: ProductionLine[]) => {
  if (selectedData && selectedData.length == 1) {
    const rowdata = selectedData.values().next().value
    ScheduledTaskQueryParam.WorkOrderId = rowdata.id

    ApiUpdateCrew_SchedulingPlanByBindWorkOrderAsync(ScheduledTaskQueryParam).then((res) => {
      if (res.data.data) {
        // 获取生产任务
        ApiGetProduction_WorkOrderByIdTaskListAsync(rowdata.id).then((res) => {
          Object.assign(WorkOrderParam, res.data.data)
          Production_WorkOrderTasks.value = res.data.data.production_WorkOrderTasks
          ProductionTaskByDetialDTO.WorkOrderId = res.data.data.id
        })
      }
    })
  } else if (selectedData.length > 1) {
    ElNotification({
      message: '只有选择一条信息，请重新选择',
      offset: 100,
      type: 'warning',
      duration: 2000
    })
  }

  // 清空工作站台存储所有选中的值
  WorkStationtSelectedValues.value = []
}

const CreateWorkOrderTaskDialog = () => {
  ScheduledTaskhandleClose()

  // ProductionTaskForm.SchedulingPlanDetials = ScheduledTaskSchedulingPlanDetial.value
  // ApiCreateProduction_ProductionTaskAsync(ProductionTaskForm).then((res) => {
  //   if (res.data.data) {
  //     ElNotification({
  //       message: '创建成功',
  //       offset: 100,
  //       type: 'success',
  //       duration: 2000
  //     })
  //     ScheduledTaskhandleClose()
  //   }
  // })
}

// -------------------------添加------------------------------

// 选择班组查询列
const queryProductionLineColumns = [
  { prop: 'productionLineName', label: '产线名称' },
  { prop: 'WorkshopName', label: '车间名称' }
]

// 选择班组信列
const ProductionLineColumns = [
  { prop: 'productionLineNo', label: '产线编码' },
  { prop: 'productionLineName', label: '产线名称' },
  { prop: 'workshop.workshopNo', label: '车间编码' },
  { prop: 'workshop.workshopName', label: '车间名称' },
  { prop: 'user.userName', label: '负责人' }
]

const CreateSchedulingPlanFormRules = reactive({
  StartTime: [{ required: true, message: '请选择', trigger: 'blur' }],
  EndTime: [{ required: true, message: '请选择', trigger: 'blur' }],
  SchedulingPlanName: [{ required: true, message: '不能为空', trigger: 'blur' }],
  TeamBillId: [{ required: true, message: '请选择', trigger: 'blur' }],
  ProductionLineId: [{ required: true, message: '请选择', trigger: 'blur' }]
})

// 产线
interface ProductionLine {
  id: ''
  ProductionLineName: null
  WorkshopId: null
  PageIndex: 1
  PageSize: 100
  totalCount: 0
}
const queryProductionLineParam = reactive({
  ProductionLineName: null,
  WorkshopId: null,
  id: '',
  totalCount: 0,
  PageIndex: 1,
  PageSize: 100
})

// 存储所有选中的值
const WorkStationtSelectedValues = ref<TeamBill[]>([])

// 计算过滤后的选项列表
const filteredWorkStationtableData = (row: string) => {
  return WorkStationtableData.value.filter((option) => {
    // 仅包含未被选中的选项或当前行选中的选项
    return !WorkStationtSelectedValues.value.includes(option.id) || option.id === row
  })
}

// 处理选中值改变事件
const WorkStationtSelectionChange = (WorkStationId: string) => {
  const WorkStationt = WorkStationtableData.value.find((item) => item.id == WorkStationId)

  // 向TeamBillDetialData添加一个工序值
  if (WorkStationt !== null) {
    //  processName 值
    const newProcessName = WorkStationt?.process.processName

    // 找到匹配的对象，并更新它
    const updatedValue = TeamBillDetialData.value.map((item) => {
      if (item.WorkStationId === WorkStationId) {
        // 如果找到匹配的 WorkStationId，复制原对象，并添加新的 processName 属性
        return {
          ...item,
          processName: newProcessName
        }
      }
      return item // 对于非匹配项，保持不变
    })

    // 更新 TeamBillDetialData.value 的值为更新后的数组
    TeamBillDetialData.value = updatedValue
  }
  updateSelectedValues()
}

//设置员工休息
const handleStatusChange = (row: any) => {
  if (row.Status >= 1) {
    WorkStationtSelectionClear(row)
    row.processName = null
  }
}

// 处理清除选中值事件
const WorkStationtSelectionClear = (row: any) => {
  // 清除当前行的选中值
  row.WorkStationId = null
  updateSelectedValues()
}

// 更新选中的值列表
const updateSelectedValues = () => {
  WorkStationtSelectedValues.value = TeamBillDetialData.value.map((data) => data.WorkStationId).filter((value) => value)
}

//工作站表格数据
const WorkStationtableData = ref([{ id: null }])

//选择工作站对话框确定操作
const handleSelectedProductionLineData = (selectedData: ProductionLine[]) => {
  if (selectedData && selectedData.length == 1) {
    const rowdata = selectedData.values().next().value
    CreateSchedulingPlanForm.ProductionLineId = rowdata.id
    CreateSchedulingPlanForm.WorkStationName = rowdata.productionLineName

    // 获取明细
    ApiGetShopfloor_ProductionLineByIdWorkStationListAsync(rowdata.id).then((res) => {
      WorkStationtableData.value = res.data.data

      TeamBillDetialData.value.forEach((data) => {
        data.WorkStationId = null
        data.processName = null
      })
      WorkStationtSelectedValues.value = []
    })
  } else if (selectedData.length > 1) {
    ElNotification({
      message: '只有选择一条信息，请重新选择',
      offset: 100,
      type: 'warning',
      duration: 2000
    })
  }

  // 清空工作站台存储所有选中的值
  WorkStationtSelectedValues.value = []
}

//打开选择产线对话框
const SelectProductionLine = () => {
  SelectProductionLineDialogVisible.value = true
  ApiGetShopfloor_ProductionLinePageListAsync(queryProductionLineParam).then((res) => {
    SelectProductionLinetableData.value = res.data.data
    queryProductionLineParam.PageIndex = res.data.pageIndex
    queryProductionLineParam.PageSize = res.data.pageSize
    queryProductionLineParam.totalCount = res.data.totalCount
  })
}

const SelectProductionLineDialogVisible = ref(false)
//选择产线对话框查询操作
const QueryProductionLineForms = (form: ProductionLine) => {
  ApiGetShopfloor_ProductionLinePageListAsync(form).then((res) => {
    SelectProductionLinetableData.value = res.data.data
  })
}

// 对话框关闭后执行的逻辑（产线）
const handleDialogClosedProductionLine = () => {
  SelectProductionLineDialogVisible.value = false
  UpdateSelectProductionLineDialogVisible.value = false
}
//选择产线表格数据
const SelectProductionLinetableData = ref([])

// 分页相关数据
const CreateProductcurrentPage = ref(1)
const CreateProductpageSize = ref(10)

// 计算当前页要显示的数据
const CreateProductcurrentPageData = computed(() => {
  const startIndex = (CreateProductcurrentPage.value - 1) * CreateProductpageSize.value
  const endIndex = Math.min(startIndex + CreateProductpageSize.value, TeamBillDetialData.value.length)
  return TeamBillDetialData.value.slice(startIndex, endIndex)
})

// 总条目数
const CreateProductTotalItems = computed(() => TeamBillDetialData.value.length)

// 处理分页大小变化的方法
const CreateProducthandleSizeChange = (val: number) => {
  CreateProductpageSize.value = val
  CreateProductcurrentPage.value = 1 // 重置页码为 1
}

// 处理当前页变化的方法
const CreateProducthandleCurrentChange = (val: number) => {
  CreateProductcurrentPage.value = val
}

// 班组成员
const TeamBillDetialData = ref<TeamBill[]>([])
//选择用户对话框确定操作
const handleSelectedTeamBillBillData = (selectedData: TeamBill[]) => {
  if (selectedData && selectedData.length == 1) {
    const rowdata = selectedData.values().next().value
    CreateSchedulingPlanForm.TeamBillId = rowdata.id
    CreateSchedulingPlanForm.TeamBillName = rowdata.teamName
    // 获取班组明细
    queryTeamBillBillParam.TeamId = rowdata.id
    ApiGetCrew_TeamBillDetialPageListAsync(queryTeamBillBillParam).then((res) => {
      TeamBillDetialData.value = res.data.data
      TeamBillDetialData.value = TeamBillDetialData.value.map((bill) => ({
        ...bill,
        Status: 0
      }))
    })
  } else if (selectedData.length > 1) {
    ElNotification({
      message: '只有选择一条信息，请重新选择',
      offset: 100,
      type: 'warning',
      duration: 2000
    })
  }
  // 清空工作站台存储所有选中的值
  WorkStationtSelectedValues.value = []
}

// 班组
interface TeamBill {
  TeamName: ''
  WorkStationId: null
  processName: null
  PageIndex: 1
  PageSize: 100
  totalCount: 0
}
//选择班组对话框查询操作
const QueryTeamBillBillForms = (form: TeamBill) => {
  ApiGetCrew_TeamBillPageListAsync(form).then((res) => {
    SelectTeamBillBilltableData.value = res.data.data
  })
}

// 对话框关闭后执行的逻辑
const handleDialogClosedTeamBillBill = () => {
  SelectTeamBillBillDialogVisible.value = false
}
//选择班组表格数据
const SelectTeamBillBilltableData = ref([])
// 选择班组查询列
const querycolumns = [{ prop: 'TeamName', label: '名称' }]

// 选择班组信列
const columns = [
  { prop: 'teamNo', label: '编码' },
  { prop: 'teamName', label: '名称' },
  { prop: 'user.jobNumber', label: '组长工号' },
  { prop: 'user.userName', label: '组长姓名' }
]

//打开选择班组对话框状态值
const SelectTeamBillBillDialogVisible = ref(false)

const queryTeamBillBillParam = reactive({
  TeamName: null,
  TeamId: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})
//打开选择班组对话框
const SelectTeamBill = () => {
  SelectTeamBillBillDialogVisible.value = true
  ApiGetCrew_TeamBillPageListAsync(queryTeamBillBillParam).then((res) => {
    SelectTeamBillBilltableData.value = res.data.data
    queryTeamBillBillParam.PageIndex = res.data.pageIndex
    queryTeamBillBillParam.PageSize = res.data.pageSize
    queryTeamBillBillParam.totalCount = res.data.totalCount
  })
}

// 创建一个响应式变量 maxHeight，初始值为屏幕高度的 80%
const maxHeight = ref(window.innerHeight * 0.6)

// 用于更新 maxHeight 的值
const updateMaxHeight = () => {
  maxHeight.value = window.innerHeight * 0.6
}

// 在组件挂载时添加一个事件监听器，监听窗口大小的变化
onMounted(() => {
  window.addEventListener('resize', updateMaxHeight)
})

// 在组件销毁前移除事件监听器，以防止内存泄漏
onBeforeUnmount(() => {
  window.removeEventListener('resize', updateMaxHeight)
})
const isFullScreen = ref(false)

//展开添加窗口
const toggleFullScreen = () => {
  isFullScreen.value = !isFullScreen.value
  if (isFullScreen.value) {
    maxHeight.value = window.innerHeight * 0.8
  } else {
    maxHeight.value = window.innerHeight * 0.6
  }
}
const CreateSchedulingPlanRules = reactive({
  SchedulingPlanName: [{ required: true, message: '排班计划名称不能为空', trigger: 'blur' }],
  Address: [{ required: true, message: '排班计划地址不能为空', trigger: 'blur' }]
})
const CreateSchedulingPlanForm = reactive({
  id: '',
  TeamBillId: '',
  TeamBillName: '',
  WorkshopId: '',
  ProductionLineId: '',
  WorkStationName: '',
  SchedulingPlanStatus: 1,
  ShiftPattern: 2
})
const centerDialogVisible = ref(false)
const CreateSchedulingPlanFormRef = ref<FormInstance>()
// 关闭创建排班计划对话框
const CreateSchedulingPlanhandleClose = () => {
  const formEl = CreateSchedulingPlanFormRef.value
  if (!formEl) return
  formEl.resetFields()
  centerDialogVisible.value = false
  TeamBillDetialData.value = []
  // 清空工作站台存储所有选中的值
  WorkStationtSelectedValues.value = []
  //清空工作站
  WorkStationtableData.value = []
  CreateSchedulingPlanForm.WorkStationName = ''
  CreateSchedulingPlanForm.ProductionLineId = ''
}

// 打开添加排班计划对话框
const addSchedulingPlan = () => {
  centerDialogVisible.value = true
}

// 确认添加排班计划
const CreateSchedulingPlanDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      const filteredData = TeamBillDetialData.value.map((data) => ({
        UserinfoId: data.id,
        WorkStationId: data.WorkStationId,
        Status: data.Status
      }))
      // .filter((item) => item.WorkStationId !== undefined && item.WorkStationId !== null)

      CreateSchedulingPlanForm.CrewSchedulingPlanDetials = filteredData

      ApiCreateCrew_SchedulingPlanAsync(CreateSchedulingPlanForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '创建成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          CreateSchedulingPlanhandleClose()
          SearchSchedulingPlan()
        }
      })
    }
  })
}

// -------------------------修改------------------------------
// 响应式变量
const UpdateDialogVisible = ref(false)

// 表单数据和验证规则
const UpdateSchedulingPlanForm = reactive({ id: '', ProductionLineId: '', ProductionLineName: '' })

// 打开更新排班计划信息对话框
const UpdateSchedulingPlan = (row: { [key: string]: string | number }) => {
  Object.assign(UpdateSchedulingPlanForm, capitalizeFirstLetter(row))
  UpdateDialogVisible.value = true
}

// 确认更新排班计划信息
const UpdateSchedulingPlanFormRef = ref<FormInstance>()
const UpdateSchedulingPlanDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      UpdateSchedulingPlanForm.CrewSchedulingPlanDetial = null
      ApiUpdateCrew_SchedulingPlanAsync(UpdateSchedulingPlanForm).then((res) => {
        if (res.data.data) {
          ElNotification({
            message: '更新成功',
            offset: 100,
            type: 'success',
            duration: 2000
          })
          UpdateDialogVisible.value = false
          SearchSchedulingPlan()
        }
      })
    }
  })
}

// -------------------------删除------------------------------

// 删除单个排班计划
const DeleteSchedulingPlanSingle = (id: string) => {
  selectedRows.value = [id]
  batchDeletionSchedulingPlan()
}

// 批量删除排班计划
const batchDeletionSchedulingPlan = () => {
  if (selectedRows.value.length < 1) {
    ElNotification({
      message: '请先选择一条或更多信息',
      type: 'warning',
      offset: 100,
      duration: 2000
    })
    return
  }
  ElMessageBox.confirm('确实要删除这些信息吗?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      ApiDeletionCrew_SchedulingPlanAsync(selectedRows.value)
        .then((res) => {
          if (res.data.data) {
            ElNotification({
              message: '删除成功',
              offset: 100,
              type: 'success',
              duration: 2000
            })
            selectedRows.value = []
            SearchSchedulingPlan()
          }
        })
        .catch(() => {
          selectedRows.value = []
        })
    })
    .catch(() => {
      selectedRows.value = []
    })
}

// --------------------------数据列表------------------------------
// 定义接口和类型
interface SchedulingPlanParam {
  SchedulingPlanName: string | null
  PageIndex: number
  PageSize: number
  totalCount: number
}
const selectedRows = ref<string[]>([]) // 存储选中的行数据
const tableloading = ref(false)
// 查询参数
const querySchedulingPlanParam: SchedulingPlanParam = reactive({
  SchedulingPlanName: null,
  PageIndex: 1,
  PageSize: 100,
  totalCount: 11
})

// 表格数据
const tableData = ref([])

// 搜索排班计划
const SearchSchedulingPlan = () => {
  tableloading.value = true
  ApiGetCrew_SchedulingPlanPageListAsync(querySchedulingPlanParam)
    .then((res) => {
      tableData.value = res.data.data
      querySchedulingPlanParam.PageIndex = res.data.pageIndex
      querySchedulingPlanParam.PageSize = res.data.pageSize
      querySchedulingPlanParam.totalCount = res.data.totalCount
    })
    .finally(() => {
      tableloading.value = false
    })
}

// 获取选择项
const handleSelectionChange = (val: SchedulingPlan[]) => {
  selectedRows.value = val.map((item) => item.id)
}

// 时间转换
const formatColumnTime = (row: object, column: string, time: string | number | Date) => {
  if (time === null) {
    return ''
  }

  if (typeof time === 'string' || typeof time === 'number') {
    return formatTime(time)
  } else {
    return formatTime(time.getTime())
  }
}

// 每页条数
const handleSizeChange = (e: number) => {
  querySchedulingPlanParam.PageSize = e
  SearchSchedulingPlan()
}

// 当前页变化
const handleCurrentChange = (e: number) => {
  querySchedulingPlanParam.PageIndex = e
  SearchSchedulingPlan()
}

// 初次加载数据
onMounted(() => {
  SearchSchedulingPlan()
})
</script>



<style lang="less"  scoped>
@import '../../assets/globle/index.css';

.my-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  align-items: center;
}

.icon-button {
  margin-left: 10px;
  cursor: pointer;
}

.full-screen-btn {
  margin-left: 10px;
}
</style>
